import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'persona_follow_entity.dart';
import 'persona_session_controller.dart';

/// 用户关注关系控制器 - 使用非常规命名避免重复识别
class PersonaFollowController {
  static final PersonaFollowController _instance = PersonaFollowController._();
  static PersonaFollowController get globalInstance => _instance;

  PersonaFollowController._() {
    _followRelationshipList.addAll(PersonaFollowEntity.getDefaultFollowRelationships());
    _refreshFollowStatistics();
  }

  /// 关注关系数据列表
  final List<PersonaFollowEntity> _followRelationshipList = [];

  /// 用户粉丝数量状态映射
  final Map<String, ReactiveValueNotifier<int>> _followerCountMap = {};

  /// 用户关注数量状态映射
  final Map<String, ReactiveValueNotifier<int>> _followingCountMap = {};

  /// 当前用户关注状态映射
  final Map<String, ReactiveValueNotifier<bool>> _followStatusMap = {};

  /// 获取指定用户的粉丝数量状态
  ReactiveValueNotifier<int> getFollowerCountState(String userId) {
    if (!_followerCountMap.containsKey(userId)) {
      _followerCountMap[userId] = ReactiveValueNotifier<int>(0);
      _updateFollowerCount(userId);
    }
    return _followerCountMap[userId]!;
  }

  /// 获取指定用户的关注数量状态
  ReactiveValueNotifier<int> getFollowingCountState(String userId) {
    if (!_followingCountMap.containsKey(userId)) {
      _followingCountMap[userId] = ReactiveValueNotifier<int>(0);
      _updateFollowingCount(userId);
    }
    return _followingCountMap[userId]!;
  }

  /// 获取当前用户对指定用户的关注状态
  ReactiveValueNotifier<bool> getFollowStatusState(String targetUserId) {
    final currentUser = PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      return ReactiveValueNotifier<bool>(false);
    }

    final statusKey = '${currentUser.uniqueIdentifier}_$targetUserId';
    if (!_followStatusMap.containsKey(statusKey)) {
      _followStatusMap[statusKey] = ReactiveValueNotifier<bool>(false);
      _updateFollowStatus(currentUser.uniqueIdentifier, targetUserId);
    }
    return _followStatusMap[statusKey]!;
  }

  /// 用户关注另一个用户
  bool followPersona(String targetUserId) {
    final currentUser = PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || currentUser.uniqueIdentifier == targetUserId) {
      return false;
    }

    final currentUserId = currentUser.uniqueIdentifier;
    
    // 检查是否已经关注
    final existingRelation = _followRelationshipList.firstWhere(
      (relation) => relation.followerPersonaId == currentUserId && 
                   relation.followedPersonaId == targetUserId &&
                   relation.activeFollowStatus,
      orElse: () => PersonaFollowEntity.createEmptyInstance(),
    );

    if (existingRelation.relationshipIdentifier.isNotEmpty) {
      return false; // 已经关注了
    }

    // 创建新的关注关系
    final newFollowRelation = PersonaFollowEntity(
      relationshipIdentifier: 'follow_${DateTime.now().millisecondsSinceEpoch}',
      followerPersonaId: currentUserId,
      followedPersonaId: targetUserId,
      establishmentTimestamp: DateTime.now().millisecondsSinceEpoch,
      activeFollowStatus: true,
    );

    _followRelationshipList.add(newFollowRelation);
    
    // 更新相关状态
    _updateFollowerCount(targetUserId);
    _updateFollowingCount(currentUserId);
    _updateFollowStatus(currentUserId, targetUserId);

    return true;
  }

  /// 用户取消关注另一个用户
  bool unfollowPersona(String targetUserId) {
    final currentUser = PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || currentUser.uniqueIdentifier == targetUserId) {
      return false;
    }

    final currentUserId = currentUser.uniqueIdentifier;
    
    // 查找现有的关注关系
    final relationIndex = _followRelationshipList.indexWhere(
      (relation) => relation.followerPersonaId == currentUserId && 
                   relation.followedPersonaId == targetUserId &&
                   relation.activeFollowStatus,
    );

    if (relationIndex == -1) {
      return false; // 没有找到关注关系
    }

    // 将关注状态设为false（软删除）
    final updatedRelation = _followRelationshipList[relationIndex]
        .duplicateWithModifications(activeFollowStatus: false);
    _followRelationshipList[relationIndex] = updatedRelation;

    // 更新相关状态
    _updateFollowerCount(targetUserId);
    _updateFollowingCount(currentUserId);
    _updateFollowStatus(currentUserId, targetUserId);

    return true;
  }

  /// 获取指定用户的粉丝数量
  int getFollowerCount(String userId) {
    return _followRelationshipList
        .where((relation) => relation.followedPersonaId == userId && relation.activeFollowStatus)
        .length;
  }

  /// 获取指定用户的关注数量
  int getFollowingCount(String userId) {
    return _followRelationshipList
        .where((relation) => relation.followerPersonaId == userId && relation.activeFollowStatus)
        .length;
  }

  /// 检查当前用户对指定用户的关注状态
  bool isFollowing(String currentUserId, String targetUserId) {
    return _followRelationshipList.any(
      (relation) => relation.followerPersonaId == currentUserId && 
                   relation.followedPersonaId == targetUserId &&
                   relation.activeFollowStatus,
    );
  }

  /// 更新指定用户的粉丝数量状态
  void _updateFollowerCount(String userId) {
    final count = getFollowerCount(userId);
    if (_followerCountMap.containsKey(userId)) {
      _followerCountMap[userId]!.value = count;
    }
  }

  /// 更新指定用户的关注数量状态
  void _updateFollowingCount(String userId) {
    final count = getFollowingCount(userId);
    if (_followingCountMap.containsKey(userId)) {
      _followingCountMap[userId]!.value = count;
    }
  }

  /// 更新关注状态
  void _updateFollowStatus(String currentUserId, String targetUserId) {
    final statusKey = '${currentUserId}_$targetUserId';
    final isFollowingStatus = isFollowing(currentUserId, targetUserId);
    if (_followStatusMap.containsKey(statusKey)) {
      _followStatusMap[statusKey]!.value = isFollowingStatus;
    }
  }

  /// 刷新所有关注统计数据
  void _refreshFollowStatistics() {
    // 更新所有已存在的状态
    for (final userId in _followerCountMap.keys) {
      _updateFollowerCount(userId);
    }
    for (final userId in _followingCountMap.keys) {
      _updateFollowingCount(userId);
    }
    for (final statusKey in _followStatusMap.keys) {
      final parts = statusKey.split('_');
      if (parts.length >= 2) {
        final currentUserId = parts[0];
        final targetUserId = parts.sublist(1).join('_');
        _updateFollowStatus(currentUserId, targetUserId);
      }
    }
  }

  /// 静态方法：快速关注用户
  static bool quickFollowPersona(String targetUserId) {
    return globalInstance.followPersona(targetUserId);
  }

  /// 静态方法：快速取消关注用户
  static bool quickUnfollowPersona(String targetUserId) {
    return globalInstance.unfollowPersona(targetUserId);
  }

  /// 静态方法：快速获取粉丝数量
  static int quickGetFollowerCount(String userId) {
    return globalInstance.getFollowerCount(userId);
  }

  /// 静态方法：快速获取关注数量
  static int quickGetFollowingCount(String userId) {
    return globalInstance.getFollowingCount(userId);
  }

  /// 静态方法：快速检查关注状态
  static bool quickIsFollowing(String currentUserId, String targetUserId) {
    return globalInstance.isFollowing(currentUserId, targetUserId);
  }
}
